package com.ziq.zcamp.util


import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView
import com.ziq.zcamp.view.edit.SupportTopicsTextHelp
import com.ziq.zcamp.view.edit.TopicsKeyModel

class TopicsUtils {

    companion object{
        @JvmStatic
        fun topicsSetColor(v: TextView, content : String?, topics : List<String>,click : (String) -> Unit = {},
                           indexOfList: Int = -1 , hashMap: HashMap<TopicsKeyModel,String> = HashMap(15)){
            v.movementMethod = LinkMovementMethod.getInstance()
            v.text = topicsColorSpan(v.currentTextColor,Color.parseColor("#FFAF8B6C"),content,topics,click,indexOfList,hashMap)
        }

        @JvmStatic
        fun topicsColorSpan(normalColor : Int ,topicsColor : Int , content : String?, topics : List<String>,click : (String) -> Unit,
                            indexOfList: Int = -1 , hashMap: HashMap<TopicsKeyModel,String> = HashMap(15)
        ):SpannableStringBuilder{
            if (content == null){
                return SpannableStringBuilder("")
            }
            if (topics.isEmpty() || content.isEmpty()){
                return SpannableStringBuilder(content)
            }else{
                val builder = SpannableStringBuilder(content)
                val backgroundColor = ForegroundColorSpan(normalColor)
                builder.setSpan(backgroundColor, 0, builder.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                try {
                    val topicsMap = SupportTopicsTextHelp.help(content,topics,indexOfList,hashMap)
                    for ((key,value) in topicsMap.entries){
                        val index = if (key.indexOfList == indexOfList) {
                            key.indexOfStr
                        } else {
                            continue
                        }
                        val end = index + value.length
                        val clickSpan = object : ClickableSpan() {
                            override fun onClick(widget: View) {
                                click.invoke(value)
                            }

                            override fun updateDrawState(ds: TextPaint) {
                                super.updateDrawState(ds)
                                ds.color = topicsColor
                                ds.isUnderlineText = false
                            }
                        }
                        builder.setSpan(clickSpan, index, end.coerceAtMost(content.length), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    }
                }catch (e :Exception){
                    e.printStackTrace()
                }
                return builder
            }
        }

    }
}